/*
 * @lc app=leetcode.cn id=25 lang=typescript
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

// 反转 start-end
function reverse(start: ListNode | null, end: ListNode | null): ListNode | null {
    let pre = null, curr = start, next = start
    while (curr !== end) {
        next = curr!.next
        curr!.next = pre
        pre = curr
        curr = next
    }
    return pre
}

//  思路：递归
//  只要考虑base，即不够翻转的情况与得到子问题结果后合并的情况
function reverseKGroup(head: ListNode | null, k: number): ListNode | null {
    let start = head, end = head

    for (let i = 0; i < k; i++) {
        // 不足以反转k个
        if (!end) return head
        end = end.next
    }

    let newHead = reverse(start, end)
    let nextHead = reverseKGroup(end, k)
    // 链表翻转，start是末尾节点，接上递归的结果
    start!.next = nextHead

    return newHead
};
// @lc code=end

import { ListNode } from './type'
let l1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))))
let l2 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))))
console.log(ListNode.printList(reverseKGroup(l1, 2)))
console.log(ListNode.printList(reverseKGroup(l2, 3)))

// console.log(ListNode.printList(reverse(l2, l2.next!.next)))

